﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MCPlatform.MotionLib.Base.AssitantClass
{
    public class Common
    {

        /// <summary>
        /// 接口/类属性映射至实体属性
        /// </summary>
        /// <param name="source">源</param>
        /// <param name="destination">目标</param>
        public static void AutoMapProperties(object source, object destination)
        {
            PropertyInfo[] sourceProperties = source.GetType().GetProperties();
            PropertyInfo[] destinationProperties = destination.GetType().GetProperties();

            foreach (var sourceProp in sourceProperties)
            {
                foreach (var destProp in destinationProperties)
                {
                    if (sourceProp.Name == destProp.Name && sourceProp.PropertyType == destProp.PropertyType && destProp.CanWrite)
                    {
                        destProp.SetValue(destination, sourceProp.GetValue(source));
                        break;
                    }
                }
            }
        }

        public static void AutoMapPropertiesNotInterface(object source, object destination)
        {
            PropertyInfo[] sourceProperties = source.GetType().GetProperties();
            PropertyInfo[] destinationProperties = destination.GetType().GetProperties();

            foreach (var sourceProp in sourceProperties)
            {
                foreach (var destProp in destinationProperties)
                {
                   
                    if (sourceProp.Name == destProp.Name && sourceProp.PropertyType == destProp.PropertyType && destProp.CanWrite)
                    {
                        // 如果属性类型为接口，则跳过映射
                        if (sourceProp.PropertyType.IsInterface)
                        {
                            break;
                        }
                        destProp.SetValue(destination, sourceProp.GetValue(source));
                        break;
                    }
                }
            }
        }




        public static string GetEnumDescription(Enum value)
        {
            FieldInfo? field = value.GetType().GetField(value.ToString());
            if (field is null)
            {
                return value.ToString();
            }

            DescriptionAttribute attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))!;

            return attribute == null ? value.ToString() : attribute.Description;
        }
    }
}
